import openai
import requests
import json

# 配置API密钥
openai.api_base = "https://api.deepseek.com"
openai.api_key = "sk-72483135d43b45bb8f349ab97425e701"


def query_deepseek(prompt):
    """使用requests库直接调用API，更稳定"""
    url = "https://api.deepseek.com/chat/completions"
    headers = {
        "Authorization": f"Bearer {openai.api_key}",
        "Content-Type": "application/json"
    }

    data = {
        "model": "deepseek-chat",  # 尝试不同的模型名称
        "messages": [
            {"role": "system", "content": "你是一个有帮助的AI助手"},
            {"role": "user", "content": prompt}
        ],
        "temperature": 0.7,
        "max_tokens": 1024
    }

    try:
        response = requests.post(url, headers=headers, json=data, timeout=30)

        if response.status_code == 200:
            result = response.json()
            return result['choices'][0]['message']['content'].strip()
        else:
            return f"API调用失败: HTTP {response.status_code} - {response.text}"

    except Exception as e:
        return f"API调用失败: {str(e)}"


def check_api_key():
    try:
        # 使用requests来检查API密钥
        url = "https://api.deepseek.com/models"
        headers = {
            "Authorization": f"Bearer {openai.api_key}",
            "Content-Type": "application/json"
        }

        response = requests.get(url, headers=headers, timeout=10)

        if response.status_code == 200:
            print("API密钥有效！")
            models = response.json()
            print("可用模型:")
            for model in models.get('data', []):
                print(f"- {model.get('id')}")
            return True
        else:
            print(f"API密钥检查失败: HTTP {response.status_code}")
            return False

    except Exception as e:
        print(f"API密钥检查错误: {e}")
        return False


import pandas as pd
import os




if __name__ == "__main__":
    if check_api_key():
        line_one = "用简单的话解释量子计算"
        print("用户提问:", line_one)
        answer = query_deepseek(line_one)
        print("\n模型回复:")
        print(answer)
    else:
        print("请检查：")
        print("1. API密钥是否正确（应以'sk-'开头）")
        print("2. API密钥是否有调用权限")
        print("3. 网络连接是否正常")
        print("4. 账户余额是否充足")